package com.briup.day20;

import java.util.*;

/**
 * @author ThinkBook
 */
public class Test02_TreeMap {
    public static void main(String[] args) {
        //1.准备一个自定义比较器对象，先按照名字降序再按照年龄升序
        Comparator<Student1> comp = new Comparator<Student1>() {
            @Override
            public int compare(Student1 o1, Student1 o2) {
                //名字降序
                int r = o2.getName().compareTo(o1.getName());
                if (r == 0){
                    //年龄升序
                    r = o1.getAge() - o2.getAge();
                }
                return  (r == 0) ? 1 : r;
            }
        };
        //2.实例化TreeMap传递比较器对象
        TreeMap<Student1,String> map = new TreeMap<>(comp);
        map.put(new Student1("zs", 78),"010");
        map.put(new Student1("rose", 82),"005");
        map.put(new Student1("lucy", 79),"009");
        map.put(new Student1("lucy", 79),"009");
        map.put(new Student1("tom", 68),"019");
        map.put(new Student1("tom", 86),"012");
        map.put(new Student1("ww", 67),"002");

        //3.遍历
      Set<Map.Entry<Student1,String>> entries = map.entrySet();
      for (Map.Entry<Student1,String> entry : entries){
          Student1 k = entry.getKey();
          String value = entry.getValue();
          System.out.println(k+":"+value);
        }
    }
    //TreeMap放入键值对，其中key实现自然排序
    public static void main01(String[] args) {
        Map<Integer,String> map = new TreeMap<>();

        map.put(3,"Jack");
        map.put(2,"lucy");
        map.put(4,"lily");
        map.put(1,"tom");
        map.put(2,"ww");

        //第二种遍历方式
        Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
        for(Map.Entry<Integer, String> entry : entrySet) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
class Student1{
    private String name;
    private int age;

    public Student1() {
    }

    public Student1(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
